package com.yhsimon.service;

import com.alibaba.fastjson.JSON;
import com.yhsimon.pojo.Commodity;
import com.yhsimon.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CommodityService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public static void main(String[] args) throws IOException {
        new CommodityService().parseContent("余华");
    }

    //1. 解析数据放入es索引中
    public Boolean parseContent(String keyword) throws IOException {
        List<Commodity> commodities = new HtmlParseUtil().parseDangDang(keyword);
        //把查询到的数据放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i=0;i<commodities.size();i++){
//            System.out.println(commodities.get(i).toString());
            bulkRequest.add(
                    new IndexRequest("dangdang_commodities")
                        .source(JSON.toJSONString(commodities.get(i)), XContentType.JSON)
            );
        }
        BulkResponse resp = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("操作是否有误："+resp.hasFailures());
        return !resp.hasFailures();
    }

    //2. 获取数据实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
        if (pageNo<=0){
            pageNo=0;
        }

        //条件查询
        SearchRequest request = new SearchRequest("dangdang_commodities");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //模糊匹配
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("title", keyword);
//        WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("title", "*" + keyword + "*");
        searchSourceBuilder.query(matchPhraseQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        //执行搜索
        request.source(searchSourceBuilder);
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : resp.getHits().getHits()) {
            list.add(documentFields.getSourceAsMap());
        }

        return list;
    }


    //3. 获取数据实现搜索功能 +高亮效果
    public List<Map<String,Object>> searchPageWithHighlight(String keyword,int pageNo,int pageSize) throws IOException {
        if (pageNo<=0){
            pageNo=0;
        }

        //条件查询
        SearchRequest request = new SearchRequest("dangdang_commodities");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //模糊匹配
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("title", keyword);
//        WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("title", "*" + keyword + "*");
        searchSourceBuilder.query(matchPhraseQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//关闭多个高亮显示
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        request.source(searchSourceBuilder);
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : resp.getHits().getHits()) {

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果
            //解析高亮的字段  将原来的字段换为高亮的字段即可
            if(title!=null){
                Text[] fragments = title.fragments();
                String newTitle="";
                for (Text text : fragments) {
                    newTitle+=text;
                }
                System.out.println("newTitle----------"+newTitle);
                sourceAsMap.put("title",newTitle); //高亮字段替换原来的内容
            }
            list.add(hit.getSourceAsMap());
        }

        return list;
    }

}
